<?php
/*
 * 聚合支付
 * */
namespace Home\Controller;

class ApiPayController extends CommonController
{

    //聚合支付
    public function jh()
    {
        //接收json post过来的文件流
        $data_r = file_get_contents('php://input');
        $data_r = json_decode($data_r, TRUE);

        //字符串变成科学计数法的处理
        $data_r['order_no'] = number_format($data_r['order_no'], 0, '', '');

        session('order_data', $data_r);

        //查询订单信息
        $where = array(
            'order_num_alias' => $data_r['order_no'],
        );

        $order_arr = M('order')->where($where)->field('order_id')->find();
        //查询商品名字
        $g_where = array(
            'order_id' => $order_arr['order_id'],
        );

        $order_data = M('order_goods')->where($g_where)->field('name')->find();

        //引进聚合支付的文件——路径
        $path = APP_PATH . '/Lib/pingpp-php/init.php';
        require_once($path);

        //聚合支付的api_key
        $ApiKey = C('API_KEY');
        \Pingpp\Pingpp::setApiKey($ApiKey);
        //\Pingpp\Pingpp::setApiKey('sk_live_Oy5qv1evT8iLb1arj9PGez9C');
        //\Pingpp\Pingpp::setPrivateKeyPath("/Modules/Lib/pingpp-php/example/your_rsa_private_key.pem");

        //$a = $this->extra_url($data_r['channel']);
        //var_dump($a);exit;
        $data_r['amount'] = $data_r['amount'] * 100;
        //聚合支付的app_id
        $App_id = C('APP_ID');

        $ch = \Pingpp\Charge::create(
            array(
                'order_no' => $data_r['order_no'],          //商品订单编号
                'app' => array('id' => $App_id),             //app_id
                'channel' => $data_r['channel'],            //支付类型
                'amount' => $data_r['amount'],              //订单总价
                'client_ip' => get_client_ip(),              //用户的ip
                'currency' => 'cny',                        //人民币
                'subject' => $order_data['name'],                       //商品
                'body' => '商品描述',   //商品描述
                'extra' => $this->extra_url($data_r['channel']),
            )
        );


        //预留id，作为退款时用
        $data = $ch;
        $array = json_decode($data, true);
        session('paying_id', $array['id']);

        echo json_encode($ch);
        die;

    }

    //支付成功回调
    public function success()
    {
        $data = I('get.');
        //跳转的页面
        $WEB_URL = C('WEB_URL') . '/order.html';
        $order_re = session('order_data');

        $paying_id = session('paying_id');
        $upate = array(
            'order_status_id' => '3',
            'pay_time' => time(),
            'payment_code' => $order_re['channel'],
            'paying_id' => $paying_id,
        );

        //$trade_no = $data['trade_no'];  //支付单号

        if ($data['out_trade_no']) {

            //查询订单信息
            $where = array(
                'order_num_alias' => $data['out_trade_no'],
            );

            $order_arr = M('order')->where($where)->field('order_id')->find();

            //订单编号去修改订单状态
            $order_data = M('order')->where($where)->save($upate);
            session('paying_id', null);

            if (!empty($order_data)) {

                $w_history = array(
                    'order_id' => $order_arr['order_id'],
                );
                M('order_history')->where($w_history)->save(array('order_status_id' => 3));

            }

            //echo "<script>parent.location.href='$WEB_URL'; </script>";
            json_data($WEB_URL);

        } elseif ($data['tradeNum']) {
            //京东支付成功的回调
            $where = array(
                'order_num_alias' => $data['tradeNum'],
            );
            //查询订单信息
            $order_arr = M('order')->where($where)->field('order_id')->find();

            //修改订单信息
            $order_data = M('order')->where($where)->save($upate);

            if (!empty($order_data)) {

                $w_history = array(
                    'order_id' => $order_arr['order_id'],
                );
                M('order_history')->where($w_history)->save(array('order_status_id' => 3));
                //跳转
                //echo "<script>alert('支付成功');parent.location.href='$WEB_URL'; </script>";
                json_data($WEB_URL);
            }
        } else {
            //支付失败
            json_error($WEB_URL);
            //echo "<script>alert('支付失败');parent.location.href='$WEB_URL'; </script>";

        }
    }


    //支付成功回调——京东支付页面
    public function fail()
    {   //跳转的页面
        $WEB_URL = C('WEB_URL') . '/order.html';
        //支付失败
        echo "<script>alert('支付失败');parent.location.href='$WEB_URL'; </script>";

    }

    //支付成功回调——京东支付页面
    public function bfd_success()
    {
        $data = I('get.');

        //跳转的页面
        $WEB_URL = C('WEB_URL') . '/order.html';

        if ($data['pay_result'] == '1') {

            $order_re = session('order_data');
            $upate = array(
                'order_status_id' => '3',
                'pay_time' => time(),
                'payment_code' => $order_re['channel'],
            );

            //百度钱包支付成功的回调
            $where = array(
                'order_num_alias' => $data['order_no'],
            );
            //查询订单信息
            $order_arr = M('order')->where($where)->field('order_id')->find();

            //修改订单信息
            $order_data = M('order')->where($where)->save($upate);

            if (!empty($order_data)) {

                $w_history = array(
                    'order_id' => $order_arr['order_id'],
                );
                M('order_history')->where($w_history)->save(array('order_status_id' => 3));
                //跳转
                echo "<script>alert('支付成功');parent.location.href='$WEB_URL'; </script>";
            }

        } else {
            echo "<script>alert('支付失败');parent.location.href='$WEB_URL'; </script>";
        }

    }

    public function extra_url($channel)
    {
        //支付成功后的回调地址
        $WEB_URL_S = C('WEB_URL') . '/index/success';
        $WEB_URL_U = C('WEB_URL') . '/index/s_success';
        $WEB_URL_F = C('WEB_URL') . '/index/fail';
        $WEB_URL_B = C('WEB_URL') . '/index/bfd_success';
        //不同的支付方式不同的回调
        switch ($channel) {
            case 'alipay_wap':
                $extra = array('success_url' => $WEB_URL_S);
                return $extra;
                break;
            case 'wx_pub':
                $extra = array('success_url' => $WEB_URL_S);
                return $extra;
                break;
            case 'upacp_wap':
                $extra = array('result_url' => $WEB_URL_U);
                return $extra;
                break;
            case 'yeepay_wap':
                $extra = array(
                    'product_category' => '7',
                    'identity_id' => 'Evan',
                    'identity_type' => '4',
                    'terminal_type' => '3',
                    'terminal_id' => '127.0.0.1',
                    'user_ua' => 'Windows',
                    'result_url' => $WEB_URL_U,
                );
                return $extra;
                break;
            case 'jdpay_wap':
                $extra = array('success_url' => $WEB_URL_S, 'fail_url' => $WEB_URL_F,);
                return $extra;
                break;
            case 'bfb_wap':
                $extra = array('bfb_login' => true, 'result_url' => $WEB_URL_B);
                return $extra;
                break;
        }
    }


    //支付成功回调——回调为空的回调(银联，易宝)
    public function s_success()
    {
        $order_re = session('order_data');

        //跳转的页面
        $WEB_URL = C('WEB_URL') . '/order.html';

        $upate = array(
            'order_status_id' => '3',
            'payment_code' => $order_re['channel'],
            'pay_time' => time(),
        );


        //查询订单信息
        $where = array(
            'order_num_alias' => $order_re['order_no'],
        );
        $order_arr = M('order')->where($where)->field('order_id')->find();

        //订单编号去修改订单状态
        $order_data = M('order')->where($where)->save($upate);

        if (!empty($order_data)) {

            $w_history = array(
                'order_id' => $order_arr['order_id'],
            );
            M('order_history')->where($w_history)->save(array('order_status_id' => 3));

        }

        echo "<script>alert('支付成功');parent.location.href='$WEB_URL'; </script>";


    }


    //Webhooks回调
    public function Webhooks()
    {
        $row_data = file_get_contents('php://input');

        //从头信息获取签名
        $headers = \Pingpp\Util\Util::getRequestHeaders();
        $signature = isset($headers['X-Pingplusplus-Signature']) ? $headers['X-Pingplusplus-Signature'] : NULL;

        //验证签名
        $pub_key_path = __DIR__ . "/certs/pingpp_webhooks_public_key.pem"; //Ping++ 公钥
        $pub_key_contents = file_get_contents($pub_key_path);
        $verify_result = openssl_verify($row_data, base64_decode($signature), $pub_key_contents, 'sha256');

        if (!$verify_result) {
            $data = array(
                'code' => 0,
                'data' => array(
                    'error_message' => 'signature verify fail',
                    'event' => $row_data
                ),
            );
            echo json_encode($data);
            die;
        } else {
            $data = array(
                'code' => 1,
                'data' => array(
                    'event' => $row_data
                ),
            );
            echo json_encode($data);
            die;
        }
    }


    public function Hj()
    {
        $order_num_alias = I('get.');
        $order_num = base64_decode($order_num_alias['order_num_alias']);
        $order_arr = M('order')->where(array('order_num_alias' => $order_num))->field('order_id,total')->find();
        $this->assign('order_num', $order_num);
        $this->assign('total', $order_arr['total']);
        $this->display('Hj/index');


    }


    //聚合支付——退款
    public function refund()
    {
        //接收json post过来的文件流
        /* $data_r = file_get_contents('php://input');
         $data_r = json_decode($data_r, TRUE);

         //字符串变成科学计数法的处理
         $data_r['order_no'] = number_format($data_r['order_no'], 0, '', '');*/
        $data_r['order_no'] = I('order_no');

        session('order_data', $data_r);

        //查询订单信息
        $where = array(
            'order_num_alias' => $data_r['order_no'],
        );

        $order_arr = M('order')->where($where)->find();

        //引进聚合支付的文件——路径
        $path = APP_PATH . '/Lib/pingpp-php/init.php';
        require_once($path);

        //聚合支付的api_key
        $ApiKey = C('API_KEY');
        \Pingpp\Pingpp::setApiKey($ApiKey);
        //\Pingpp\Pingpp::setApiKey('sk_live_Oy5qv1evT8iLb1arj9PGez9C');
        //\Pingpp\Pingpp::setPrivateKeyPath("/Modules/Lib/pingpp-php/example/your_rsa_private_key.pem");

        //$a = $this->extra_url($data_r['channel']);
        //var_dump($a);exit;
        $data_r['amount'] = $order_arr['total'] * 100;

        //聚合支付的api_key
        $ApiKey = C('API_KEY');
        \Pingpp\Pingpp::setApiKey($ApiKey);

        // Ping++ 流水号	ch_9i9uf1PWX10SDGejTSqj58i9

        $ch_id = $order_arr['paying_id'];
        $ch = \Pingpp\Charge::retrieve($ch_id);

        $ch->refunds->create(
            array(
                'amount' => $data_r['amount'],
                'description' => '退款'
            )
        );

        $re = json_encode($ch);
        if ($re['order_no']) {

            $model = D('OrderReturnGoods');
            $r_where = array(
                'order_num' => $re['order_no'],
            );
            $up = array(
                'status' => '12',
            );
            $re = $model->editReturn($r_where, $up);
            json_data('退款成功');
        }

    }


}